// purchaseUiAction.js
import { TestConfig } from "../common/testConfig.js";
import { TestSimulateData } from "../testMgr/testSimulateData.js";
import {
    getPurchaseContractData,
    getPurchaseDetailInfo,
    updateOrCreatePurchaseContract,
    reviewPurchaseOrder,
    withdrawReviewAndDeleteOrder,
    getPurchaseContractDetailData
} from "../../network/api.js";
import { ApiReturnStruct, getApiData, CommunicationPageData, NetworkParser } from "../../network/communicationConverter.js";
import { Engine } from "../engine.js";
import { DataPage } from "../../network/communicationConverter.js";
import { DocType } from '../common/docDefinition.js';
import { PurchaseContract } from "../purchase/purchaseContract.js";
import { OrderResult } from "../common/orderResult.js";
import { MessageUtil } from '@/utils/MessageUtil.js';
import { CommodityBatchWithTax } from "../sales/sales.js";

/**
 * 采购单相关UI操作类
 */
export class PurchaseUiAction {

/**
 * 获取采购单商品明细列表数据
 * @param {Object} options - 参数选项
 * @param {string} options.orgId - 组织ID
 * @param {DataPage} options.pageInfo - 分页信息
 * @param {Object} [options.filter] - 过滤条件
 * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
 * @returns {Promise<ApiReturnStruct>}
 */
async getPurchaseCommoditiesListByPage({
    orgId = null,
    pageInfo = null,
    filter = null,
    showLoadingPage = true
}) {
    if (TestConfig.purchaseContractTest) {
        // 模拟延迟
        await new Promise(resolve => setTimeout(resolve, 1000));

        let simData = new CommunicationPageData();
        const testSimulateData = new TestSimulateData();

        // 模拟采购单商品明细数据
        simData.dataList = testSimulateData.simSalesCommodityBatch();

        let ret = new ApiReturnStruct();
        ret.data = simData;

        return ret;
    } else {
        orgId = orgId ?? Engine.profile.org.orgId;
        return await getApiData(
            CommodityBatchWithTax.fromJson_metalPurchaseTradeMode, // 假设有对应的商品明细类
            orgId,
            pageInfo,
            getPurchaseContractDetailData,
            filter,
            showLoadingPage
        );
    }
}    

/**
 * 获取采购单列表数据
 * @param {Object} options - 参数选项
 * @param {string} options.orgId - 组织ID
 * @param {DataPage} options.pageInfo - 分页信息
 * @param {Object} [options.filter] - 过滤条件
 * @param {boolean} [options.showLoadingPage=true] - 是否显示加载页面
 * @returns {Promise<ApiReturnStruct>}
 */
async getPurchaseContractData({
    orgId = null,
    pageInfo = null,
    filter = null,
    showLoadingPage = true
}) {
    if (TestConfig.purchaseContractTest) {
        // 模拟延迟
        await new Promise(resolve => setTimeout(resolve, 1000));

        let simData = new CommunicationPageData();
        const testSimulateData = new TestSimulateData();

        if (filter != null && filter['b_orderStatus'] == null) {
            simData.dataList = testSimulateData.simStatePurchaseContractData(null);
        } else if (filter != null && filter['b_orderStatus'] === 0) {
            simData.dataList = testSimulateData.simStatePurchaseContractData(CommonOrderStatus.WaitReview);
        } else if (filter != null && filter['b_orderStatus'] === 1) {
            simData.dataList = testSimulateData.simStatePurchaseContractData(CommonOrderStatus.Passed);
        } else {
            simData.dataList = testSimulateData.simStatePurchaseContractData(null);
        }

        let ret = new ApiReturnStruct();
        ret.data = simData;

        return ret;
    } else {
        orgId = orgId ?? Engine.profile.org.orgId;
        return await getApiData(
            PurchaseContract.fromJson,
            orgId,
            pageInfo,
            getPurchaseContractData,
            filter,
            showLoadingPage
        );
    }
}

    /**
     * 获取采购单详情
     * @param {string} orderId - 采购单ID
     * @returns {Promise<PurchaseContract|null>}
     */
    async getPurchaseDetailInfo(orderId) {
        if (TestConfig.purchaseContractTest) {
            // 模拟延迟
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 模拟数据
            const testSimulateData = new TestSimulateData();
            let purchaseData = testSimulateData.simStatePurchaseContractData();

            // 查找匹配的元素
            let purchaseContract = purchaseData.find(item => item.id === orderId);
            if (purchaseContract) {
                return purchaseContract;
            }

            return testSimulateData.simStatePurchaseContractData()[0];
        } else {
            let res = await getPurchaseDetailInfo(orderId, Engine.profile.org.orgId);

            // 解析数据
            const apiResult = NetworkParser.parseNetworkResult(res, PurchaseContract.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /**
     * 创建或更新采购单
     * @param {PurchaseContract} purchaseContract - 采购单数据
     * @param {boolean} toAudit - 是否审核
     * @returns {Promise<OrderResult|null>}
     */
    async updateOrCreatePurchaseContract(purchaseContract, toAudit) {
        const res = await updateOrCreatePurchaseContract(purchaseContract, toAudit);

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
     * 审核采购单
     * @param {Array<string>} ids - 采购单ID列表
     * @param {string} orgId - 组织ID
     * @returns {Promise<any>}
     */
    async reviewPurchaseOrder(ids, orgId = null) {
        orgId = orgId ?? Engine.profile.org.orgId;

        const res = await reviewPurchaseOrder(ids, orgId);

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("审核采购单失败:" + apiResult.resErr);
            return apiResult;
        }

        return apiResult;
    }

    /**
     * 删除采购单
     * @param {Object} options - 参数选项
     * @param {string} options.orderId - 订单ID
     * @param {DocType} options.docType - 单据类型
     * @returns {Promise<any|null>}
     */
    async removePurchaseOrder({
        orderId,
        docType
    }) {
        const res = await withdrawReviewAndDeleteOrder({
            orderId: orderId,
            orderType: docType
        });

        // 解析数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null && typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除采购单据失败:" + apiResult.resErr);
            return apiResult;
        }

        return null;
    }

    /**
     * 显示采购单详情页面
     * @param {string} purchaseId - 采购单ID
     * @param {boolean} editMode - 是否编辑模式
     */
    async showPurchaseDetailPage(purchaseId, { editMode = false } = {}) {
        if (purchaseId) {
            uni.navigateTo({
                url: `/pages/purchase/purchaseDetailPage?purchaseId=${purchaseId}&editMode=${editMode}`
            });
        } else {
            let store = Engine.profile?.getValideStore;
            let storeParam = "";
            if (store) {
                storeParam = "&storeId=" + store.id + "&storeName=" + store.name;
            }

            uni.navigateTo({
                url: `/pages/purchase/purchaseDetailPage?editMode=${editMode}` + storeParam
            });
        }
    }
}